package com.moyuaninfo.utils;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

/**
 * 条件构造器
 *
 * @author 邱祥霸
 * @date 2020-04-07
 */
public class QueryWapper<T>{
    private Root<T> root;

    private CriteriaQuery<?> criteriaQuery;

    private CriteriaBuilder criteriaBuilder;

    private List<Predicate> predicateList = new ArrayList<>();

    public QueryWapper(Root<T> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
        this.root = root;
        this.criteriaQuery = criteriaQuery;
        this.criteriaBuilder = criteriaBuilder;
    }

    public void equal(String attribute, String value) {
        predicateList.add(criteriaBuilder.equal(root.get(attribute), value));
    }

    public Predicate getRestriction() {
        Predicate[] predicateArr = predicateList.toArray(new Predicate[predicateList.size()]);
        return criteriaQuery.where(predicateArr).getRestriction();
    }
}
